package utils

import (
	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/handler"
	"gitlab.zhijiasoft.com/paperless-group/saas-common/errorx"
	"net/http"
)

func NewCustomUnauthorizedCallback() handler.UnauthorizedCallback {
	return func(w http.ResponseWriter, r *http.Request, err error) {
		w.WriteHeader(http.StatusOK)
		data, err := json.Marshal(errorx.NewCodeError(401, "请登录").WithCode(http.StatusUnauthorized).Data())
		if err != nil {
			logx.Error(err)
		}
		w.Write(data)
		logx.Errorw("Unauthorized", logx.Field("detail", r.Header.Get("Authorization")))

		return
	}
}

type NotAllowedHandler struct {
}

func (h *NotAllowedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	data, err := json.Marshal(errorx.NewCodeError(403, "当前用户无权限访问").WithCode(http.StatusForbidden).Data())
	if err != nil {
		logx.Error(err)
	}
	w.Write(data)
	logx.Errorw("Unauthorized", logx.Field("detail", r.Header.Get("Authorization")))

	return
}

func NewCustomNotAllowedCallback() http.Handler {
	return &NotAllowedHandler{}
}
